# !/usr/bin/env python
# encoding: utf-8

'''
@author: caopeng
@license: (C) Copyright 1999-2017, Fiberhome Telecommunication Technologies Co.,LTD.
@contact: gjzuo@fiberhome.com
@software: garner
@file: get_vnfs_info.py
@time: 2018/2/7 10:51
@desc:
'''

import commands

QEMU_TYPE = "qemu-system-x86_64"
SPICE_PORT = "port"
MAC = "mac"
IP = "ip"
g_interface = ""


def get_vnf_info():
    (status, output) = commands.getstatusoutput('ps -ef | grep libvirt+')

    if status != 0:
        print("command ps -ef | grep libvirt+ exec error!")
        return False

    arr = output.split('\n')

    for psInfo in arr:
        if psInfo.find(QEMU_TYPE) == -1:
            index = arr.index(psInfo)
            arr.pop(index)

    vnfInfo = []
    for psInfo in arr:
        tmp_obj = {}
        ret1 = get_param_from_str(SPICE_PORT, psInfo, tmp_obj)
        ret2 = get_param_from_str(MAC, psInfo, tmp_obj)

        if ret1 == True:
            #通过MAC，利用arp获取虚拟机IP
            arp_command = 'arp -a | grep "%s" | cut -f 2 -d " " | sed "s/[()]//g"' %tmp_obj[MAC]
            (status, ip) = commands.getstatusoutput(arp_command)
            if status == 0:
                tmp_obj[IP] = ip


        if ret1 == True and ret2 == True:
            vnfInfo.append(tmp_obj)

    print vnfInfo




def get_param_from_str(param, str, source_obj):
    if not str or not param:
        print("parameters not valid!")
        return False
    if str.find(QEMU_TYPE) == -1:
        print("not valid string, no qemu-system-x86_64")
        return False
    paramArray = str.split(",")
    find_result = 0
    for item in paramArray:
        if(item.find(param)) != -1:
            index = item.find(param)
            ret = item[index+len(param)+1:]
            source_obj[param] = ret
            find_result = 1
        else:
            continue
    if find_result == 1:
        return True
    else:
        return False

if __name__ == '__main__':
    get_vnf_info()

